//
//  WeixinHelper.m
//  BeautyVideos
//
//  Created by 向明宗 on 16/7/25.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "WeixinHelper.h"
#import "WXApi.h"
#import <sys/socket.h>
#import <sys/sockio.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <arpa/inet.h>
#import <CommonCrypto/CommonDigest.h>
#import "MBProgressHUD.h"
#import "XLUserInfoModel.h"
#import "XLAccountManager.h"
#import "XLHTTPSessionManager+UserInfo.h"
#import <ReactiveCocoa.h>



@interface WeixinHelper()
@property (nonatomic, copy) NSString *WXPartnerKey;//秘钥
@end
@implementation WeixinHelper
+(instancetype)sharedWeixinHelper {
    static dispatch_once_t onceToken;
    static WeixinHelper *instance;
    dispatch_once(&onceToken, ^{
        instance = [[WeixinHelper alloc] init];
    });
    return instance;
}

- (void)getUrlWithWXMoney:(NSString *)money  Months:(NSString *)monthNum  TranstypeId:(NSString *)transtype  RemarksInfo:(NSString *)remark KKOrder:(NSString *)thirdorder  kkUserid:(NSString *)kkuserid{
    XLUserInfoModel *userInfoModel = [[XLAccountManager shareInstance] model];
    NSString *uid = userInfoModel.Id;
    NSString *ip = [self getDeviceIPAddress];
    UIWindow * widows = [UIApplication sharedApplication].keyWindow;
    [MBProgressHUD showHUDAddedTo:widows animated:YES];
    if ([[NSString stringWithFormat:@"%@",uid] isEqualToString:@"0"]  || [[NSString stringWithFormat:@"%@",transtype] isEqualToString:@"0"]) {
    }else{
        [[[XLHTTPSessionManager sharedManager] getWechatPayOrderWithUserId:uid GiftId:@"1" TransType:transtype PayType:@"5" FeeType:@"" Money:money PrivateInfo:[UserDefaults objectForKey:wxGlobPrivate] Remarks:remark Months:monthNum userIp:ip AppId:[UserDefaults objectForKey:wxGlobAppID] secretKey:[[XLAccountManager shareInstance] model].SecretKey] subscribeNext:^(id x) {
            NSLog(@"===微信创建订单====%@",x);
            NSString * successState = [NSString stringWithFormat:@"%@",x[@"success"]];
            if ([successState isEqualToString:@"0"]) {

                [self getweixinWithAppID:x[@"data"][@"AppId"] nonceStr:x[@"data"][@"Noncestr"] paySign:x[@"data"][@"Sign"] prepay_id:x[@"data"][@"Prepayid"] partnerid:x[@"data"][@"Partnerid"] package:x[@"data"][@"Package"]];
               }else{

                   [HelpTool startTipViewWithText:@"创建订单失败~请重试!" duration:2.0f type:kTipViewTypeNone];

            }
            [MBProgressHUD hideHUDForView:widows animated:YES];
        } error:^(NSError *error) {
            [MBProgressHUD hideHUDForView:widows animated:YES];
        }];
    }
}
- (void)getweixinWithAppID:(NSString *)appid nonceStr:(NSString *)noncestr paySign:(NSString *)paySign prepay_id:(NSString *)prepayid partnerid:(NSString *)partnerid package:(NSString *)package {
        PayReq* req = [[PayReq alloc] init];
        req.nonceStr = noncestr;
        req.partnerId = partnerid;
        req.prepayId = prepayid;
     NSDate *datenow = [NSDate date];
     NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]];
     UInt32 timestamp = [timeSp intValue];
        req.timeStamp = timestamp;
        req.package = package;
        req.sign = [self getSignAppid:appid partnerid:partnerid prepayid:prepayid nonceStr:noncestr timeStamp:timestamp package:package];
       [WXApi sendReq:req];
}
- (NSString *)getSignAppid:(NSString *)appid partnerid:(NSString *)partnerid prepayid:(NSString *)prepayid nonceStr:(NSString *)noncestr timeStamp:(UInt32)timestamp package:(NSString *)package {
    NSMutableDictionary *signParams = [NSMutableDictionary dictionary];
    [signParams setObject:appid forKey:@"appid"];
    [signParams setObject:noncestr forKey:@"noncestr"];
    [signParams setObject:package forKey:@"package"];
    [signParams setObject:partnerid forKey:@"partnerid"];
    [signParams setObject:prepayid forKey:@"prepayid"];
    [signParams setObject:[NSString stringWithFormat:@"%u",timestamp] forKey:@"timestamp"];
    NSMutableString *contentString  =[NSMutableString string];
    NSArray *keys = [signParams allKeys];
    //按字母顺序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    //拼接字符串
    for (NSString *categoryId in sortedArray) {
        if (![[signParams objectForKey:categoryId] isEqualToString:@""]
            && ![[signParams objectForKey:categoryId] isEqualToString:@"sign"]
            && ![[signParams objectForKey:categoryId] isEqualToString:@"key"]
            )
        {
            [contentString appendFormat:@"%@=%@&", categoryId, [signParams objectForKey:categoryId]];
        }
    }
    NSLog(@"====-=--=-====--%@", contentString);
    //添加商户密钥key字段
    [contentString appendFormat:@"key=%@", [UserDefaults objectForKey:wxGlobPrivate]];
    NSString *result = [self md5:contentString];
    NSLog(@"-------------%@", result);
    return result;
}

- (NSString *)md5:(NSString *)input {
    const char *cStr = [input UTF8String];
    //加密规则，因为逗比微信没有出微信支付demo，这里加密规则是参照安卓demo来得
    unsigned char result[16]= "0123456789abcdef";
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    //这里的x是小写则产生的md5也是小写，x是大写则md5是大写，这里只能用大写，逗比微信的大小写验证很逗
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}
//获取IP地址
- (NSString *)getDeviceIPAddress {
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    
    if (sockfd < 0) return nil;
    
    NSMutableArray *ips = [NSMutableArray array];
    
    int BUFFERSIZE = 4096;
    
    struct ifconf ifc;
    
    char buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;
    
    struct ifreq *ifr, ifrcopy;
    
    ifc.ifc_len = BUFFERSIZE;
    
    ifc.ifc_buf = buffer;
    
    if (ioctl(sockfd, SIOCGIFCONF, &ifc) >= 0){
        
        for (ptr = buffer; ptr < buffer + ifc.ifc_len; ){
            
            ifr = (struct ifreq *)ptr;
            int len = sizeof(struct sockaddr);
            
            if (ifr->ifr_addr.sa_len > len) {
                
                len = ifr->ifr_addr.sa_len;
                
            }
            
            ptr += sizeof(ifr->ifr_name) + len;
            
            if (ifr->ifr_addr.sa_family != AF_INET) continue;
            
            if ((cptr = (char *)strchr(ifr->ifr_name, ':')) != NULL) *cptr = 0;
            
            if (strncmp(lastname, ifr->ifr_name, IFNAMSIZ) == 0) continue;
            
            memcpy(lastname, ifr->ifr_name, IFNAMSIZ);
            
            ifrcopy = *ifr;
            
            ioctl(sockfd, SIOCGIFFLAGS, &ifrcopy);
            
            if ((ifrcopy.ifr_flags & IFF_UP) == 0) continue;
            
            NSString *ip = [NSString  stringWithFormat:@"%s", inet_ntoa(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr)];
            
            [ips addObject:ip];
            
        }
        
    }
    
    close(sockfd);
    NSString *deviceIP = @"";
    for (int i=0; i < ips.count; i++) {
        if (ips.count > 0) {
            deviceIP = [NSString stringWithFormat:@"%@",ips.lastObject];
            
        }
    }
    return deviceIP;
}
//// 签名
//- (NSString *)genSign:(NSDictionary *)signParams {
//    // 排序
//    NSArray *keys = [signParams allKeys];
//    NSArray *sortedKeys = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
//        return [obj1 compare:obj2 options:NSNumericSearch];
//    }];
//    // 生成
//    NSMutableString *sign = [NSMutableString string];
//    for (NSString *key in sortedKeys) {
//        [sign appendString:key];
//        [sign appendString:@"="];
//        [sign appendString:[signParams objectForKey:key]];
//        [sign appendString:@"&"];
//    }
//    NSString *signString = [[sign copy] substringWithRange:NSMakeRange(0, sign.length - 1)];
//    NSString *result = [self sha1:signString];
//    NSLog(@"--- Gen sign: %@", result);
//    return result;
//}

@end
